package bidsanity

import static org.junit.Assert.*
import org.junit.*
import grails.test.mixin.Mock
import grails.plugin.jms.JmsService
import grails.plugin.jms.Queue

@Mock([Customer, Listing, Bid, CustomerService])
class ListingServiceIntegrationTests {

    def listingService
    def bidService
    def john
    def tim

    @Before
    void setUp() {
        // Setup logic here
        String domain = "test.bidsanity.net"
        john = new Customer(emailAddress: "John@$domain", password: 'testtest').save()
        tim = new Customer(emailAddress: "Tim@${domain}", password: 'testtest').save()
    }

    @After
    void tearDown() {
        // Tear down logic here
        Customer.list()*.delete()
        Listing.list()*.delete()
        Bid.list()*.delete()
    }

    @Test
    void testListingCompleteNoBids() {

        def wasCalled = false;
        ListingEndTask.metaClass.sendJMSMessage= {String queueName, String message->wasCalled = queueName=="listing.nobids"}

        use( [groovy.time.TimeCategory] ){
            def listingParams = [name: "No Bid Listing", endDate: new Date() + 2.seconds, startingBidPrice: 2700,
                    description: "a listing without bids", sellerId: john.id, winner: null]
            listingService.createListing(listingParams)
        }
        
        Thread.sleep(5000)

        assertTrue(wasCalled)
    }

    @Test
    void testListingCompleteWithBids() {

        def wasCalled = false;
        def queue = ""
        ListingEndTask.metaClass.sendJMSMessage= {String queueName, String message->
            wasCalled = (queueName=="listing.complete")
            queue = queueName
        }
        def listing
        use( [groovy.time.TimeCategory] ){
            def listingParams = [name: "No Bid Listing", endDate: new Date() + 3.seconds, startingBidPrice: 2700,
                    description: "a listing without bids", sellerId: john.id]
            listing = listingService.createListing(listingParams)
        }
        
        bidService.createBid(tim.id, 2800, listing.id, null)

        Thread.sleep(5000)

        assertTrue(wasCalled)
    }
}
